package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.entity.SysUser;
import com.powernode.entity.SysUserRole;
import com.powernode.mapper.SysUserRoleMapper;
import com.powernode.service.SysUserRoleService;
import com.powernode.service.SysUserService;
import com.powernode.mapper.SysUserMapper;
import com.powernode.util.AuthUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author yanju
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2024-11-01 16:01:33
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    /**
     * 新增管理员
     * 1.新增管理员
     * 2.新增管理员和角色的关系
     * @param sysUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        //新增管理员
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        int i = sysUserMapper.insert(sysUser);
        if (i > 0){
            //获取管理员表示
            Long userId = sysUser.getUserId();
            //新增管理员与角色的关系
            //获取管理员的角色id集合
            List<Long> roleIdList = sysUser.getRoleIdList();
            //判断是否有值
            if (CollectionUtil.isNotEmpty(roleIdList)){
                //创建管理员与角色关系的集合
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                //循环遍历角色id集合
                roleIdList.forEach(roleId -> {
                    //创建管理员和角色的关系
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);;
                    sysUserRoleList.add(sysUserRole);
                });
                //批量添加管理员与角色的关系
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return i;
    }

    /**
     * 根据标识查询系统管理员信息
     */
    @Override
    public SysUser querySysUserInfoByUserId(Long id) {
        //根据标识查询管理员信息
        SysUser sysUser = sysUserMapper.selectById(id);
        //根据用户标示查询管理员与角色关系集合
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id));
        //判断是否有值
        if (CollectionUtil.isNotEmpty(sysUserRoleList)){
            //从管理员与角色关系集合中获取角色id集合
            List<Long> roldIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roldIdList);
        }
        return sysUser;
    }

    /**
     * 修改管理员信息
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer modifySysUserInfo(SysUser sysUser) {
        //获取管理员标识
        Long userId = sysUser.getUserId();
        //删除原有管理员与决定关系记录
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId));
        //添加管理员与角色关系记录
        //获取管理员的角色id集合
        List<Long> roleIdList = sysUser.getRoleIdList();

        if (CollectionUtil.isNotEmpty(roleIdList)){
            //创建管理员与角色关系的集合
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            //循环遍历
            roleIdList.forEach(roleId -> {
                //创建管理员与角色的关系
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                /*
                    新增管理员与角色的关系：不建议在循环中操作数据库
                 */
                sysUserRoleList.add(sysUserRole);
            });
            //批量添加管理员与角色的关系
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        //修改管理员信息
        //获取新密码（有值说明修改了密码没有值就是没有修改）
        String newPassword = sysUser.getPassword();
        if (StrUtil.isNotBlank(newPassword)){
            sysUser.setPassword(passwordEncoder.encode(newPassword));//需要密码加密器，在启动类里加
        }

        return sysUserMapper.updateById(sysUser);
    }

    /**
     * 批量/单个删除管理员
     * 1.删除管理员与角色的关系记录
     * 2.删除管理员
     * @param userIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSysUserListByUserIds(List<Long> userIds) {
        //1.批量/单个删除管理员与角色的关系记录
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId,userIds));

        //2.批量/单个删除管理员
        return sysUserMapper.deleteBatchIds(userIds) == userIds.size();
    }


}




